package com.hermit.qmst.tools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * 选择本地图片工具类 <br>
 * 因为直接获取图片容易崩溃，所以直接存入SD卡，再获取 <br>
 * 又因为写法不正确容易导致部分机型无法使用，所以封装起来复用 <br>
 * 使用方法： <br>
 * 1、调用getByAlbum、getByCamera去获取图片 <br>
 * 2、在onActivityResult中调用本工具类的onActivityResult方法进行处理 <br>
 * 3、onActivityResult返回的Bitmap记得空指针判断
 * 
 * <br>
 * <br>
 * PS：本工具类只能处理裁剪图片，如果不想裁剪，不使用本工具类的onActivityResult，自己做处理即可
 * 
 * @author linin630
 *
 */
public class SelectPicUtil {

	/** 临时存放图片的地址，如需修改，请记得创建该路径下的文件夹 */
	@SuppressLint("SdCardPath")
	public static String img_url = "/sdcard/temp.jpg";
	public static final String lsimg = "file://" + img_url;
	public static final int GET_BY_ALBUM = 801;// 如果有冲突，记得修改
	public static final int GET_BY_CAMERA = 802;// 如果有冲突，记得修改
	public static final int CROP = 803;// 如果有冲突，记得修改
	private static String TAG = "SelectPicUtil";
	private static Uri comUri;

	/**
	 * 选择照片
	 */
	public static void showPicDialog(final Activity act) {
		new AlertDialog.Builder(act).setCancelable(true).setTitle("图片来源")
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						SelectPicUtil.getByAlbum(act);
					}
				}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						SelectPicUtil.getByCamera(act);
					}
				}).show();
	}

	/** 从相册获取图片 */
	public static void getByAlbum(Activity act) {
		Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
		getAlbum.setType("image/*");
		act.startActivityForResult(getAlbum, GET_BY_ALBUM);
	}

	/** 通过拍照获取图片 */
	public static void getByCamera(Activity act) {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File outputImage = new File(Environment.getExternalStorageDirectory(), "out_image.jpg");
			comUri = Uri.fromFile(outputImage);
			getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, comUri);
			getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
			act.startActivityForResult(getImageByCamera, GET_BY_CAMERA);
		} else {
			Log.e(TAG, "请确认已经插入SD卡");
		}
	}

	/**
	 * 处理获取的图片，注意判断空指针，默认大小480*480，比例1:1
	 */
	public static Bitmap onActivityResult(Activity act, int requestCode, int resultCode, Intent data) {
		return onActivityResult(act, requestCode, resultCode, data, 0, 0, 0, 0);
	}

	/**
	 * 处理获取的图片，注意判断空指针
	 */
	public static Bitmap onActivityResult(Activity act, int requestCode, int resultCode, Intent data, int w, int h,
			int aspectX, int aspectY) {
		Bitmap bm = null;
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case GET_BY_ALBUM:
				// 从相册选取成功后，需要从Uri中拿出图片的绝对路径，再调用剪切
				Uri newUri = Uri.parse("file:///" + getPath(act, data.getData()));
				if (newUri != null) {
					act.startActivityForResult(crop(newUri, w, h, aspectX, aspectY), CROP);
				}
				break;
			case GET_BY_CAMERA:
				act.startActivityForResult(crop(comUri, w, h, aspectX, aspectY), CROP);
				break;
			case CROP:
				bm = dealCrop(act);
				break;
			}
		}
		return bm;

	}

	/** 默认裁剪输出480*480，比例1:1 */
	public static Intent crop(Uri uri) {
		return crop(uri, 480, 480, 1, 1);
	}

	/**
	 * 裁剪，例如：输出100*100大小的图片，宽高比例是1:1
	 * 
	 * @param w
	 *            输出宽
	 * @param h
	 *            输出高
	 * @param aspectX
	 *            宽比例
	 * @param aspectY
	 *            高比例
	 */
	public static Intent crop(Uri uri, int w, int h, int aspectX, int aspectY) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		Log.d(TAG, lsimg);
		// 照片URL地址
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		if (w == 0 && h == 0 && aspectX == 0 && aspectY == 0) {
		} else {
			intent.putExtra("aspectX", aspectX);
			intent.putExtra("aspectY", aspectY);
			intent.putExtra("outputX", w);
			intent.putExtra("outputY", h);
		}
		// 输出路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse(lsimg));
		// 输出格式
		intent.putExtra("outputFormat", "JPEG");
		// 不启用人脸识别
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", false);
		return intent;
	}

	/** 处理裁剪，获取裁剪后的图片 */
	public static Bitmap dealCrop(Context context) {
		// 裁剪返回
		Uri uri = Uri.parse(lsimg);
		System.err.println(lsimg);
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	@SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}

			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				Uri contentUri = null;
				contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();
			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}
		return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context
	 *            The context.
	 * @param uri
	 *            The Uri to query.
	 * @param selection
	 *            (Optional) Filter used in the query.
	 * @param selectionArgs
	 *            (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}
}